×
☰ See All Chapters

Handling JavaScript prompt in Selenium Webdriver

WebDriver provides an “Alert” class for handling prompt popup. “Alert” class handles all alert, confirm, and prompt javascript popups. When a prompt popup is displayed, we have to switch to prompt popup to access it. To access the prompt box displayed on the screen as an instance of the “Alert” class, the “driver.switchTo().alert()” method is used as follows:

driver.findElement(By.id("prompt")).click();               

Alert alert = driver.switchTo().alert();

 “NoAlertPresentException” exception will be thrown if there is no prompt present and “driver.switchTo().alert()” is called.

Input is sent to prompt popup via the “sendKeys()” method.

alert.sendKeys("www.tools4testing.com");

“getText()” method of the “Alert” class returns the text displayed on alert popup.

String textOnAlert = alert.getText();

To click on “OK” button on confirm popup “accept()” method is called.

alert.accept();

To dismiss or cancel confirm popup “dismiss()” method is called.

alert.dismiss();

The below example explains how to automate javascript alert pop up.

import org.openqa.selenium.Alert;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;

import org.junit.Assert;

 

public class Example {

 

        public static void main(String[] args) {

 

 

                // configure chromedriver

                System.setProperty("webdriver.chrome.driver", "F:\\My_Programs\\Selenium\\ChromeDriver\\chromedriver.exe");

 

                WebDriver driver = new ChromeDriver();

               

                // Launch website

                driver.get("https://www.tools4testing.com/contents/selenium/testpages/handling-javascript-pop-ups-testpage");

               

                driver.findElement(By.id("prompt")).click();       

                WebDriverWait wait = new WebDriverWait(driver, 20);

                Alert promptAlert  = wait.until(ExpectedConditions.alertIsPresent());

                promptAlert.sendKeys("www.tools4testing.com");

                String textOnPrompt = alert.getText();

                Assert.assertEquals(textOnPrompt, "www.tools4testing.com");

                confirmAlert.accept();

               

                //wait some time before closing

                try {

                        Thread.sleep(7000);

                } catch (InterruptedException ie) {

                }

                System.out.println("-------------------------------DONE----------------------------------");

               

                //close the driver

                driver.quit();

       

        }

}

You can write the script and test these using our Test Page

handling-javascript-prompt-in-selenium-webdriver-0
 

All Chapters
Author